package com.dx.weichat.weichat.controller;

import com.dx.weichat.weichat.entity.WxAccessToken;
import com.dx.weichat.weichat.redisUtils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;



/**
 * @author: dx
 * @date: 2018/10/7/0007
 * @description:
 */
@Controller
@RequestMapping("/redis")
public class RedisController {
	private static Logger logger = LoggerFactory.getLogger(RedisController.class);
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private RestTemplate restTemplate;
	@Value("${wechat.accessToken.url}")
	private String access_token_url;
/*
	private String appid;

	private String secret;

	private String grant_type;*/
	@ResponseBody
	@RequestMapping("/getKeyByName")
	public String getKey(@RequestParam String key){
		logger.info("========================任务调度结束 获取到的access_token:{}=========================","shiro");
		return String.valueOf(redisUtil.get(key));
	}

	@ResponseBody
	@RequestMapping("/setKeyValue")
	public String setKey(@RequestParam String key,@RequestParam String value,Long timeout){
		if(StringUtils.isEmpty(timeout)) {
			if (redisUtil.set(key, value)) {
				return "success";
			} else {
				return "failure";
			}
		}else{
			if (redisUtil.set(key, value,timeout)) {
				return "success";
			} else {
				return "failure";
			}
		}
	}

	@RequestMapping("/getAccessToken")
	@ResponseBody
	public String getAccessToken(){
		String accessToken = String.valueOf(redisUtil.get("access_token"));
		if("null"==accessToken){
			WxAccessToken wxAccessToken = restTemplate.getForObject(access_token_url,WxAccessToken.class);
			if(wxAccessToken.getErrcode()==null) {
				accessToken = wxAccessToken.getAccess_token();
				redisUtil.set("access_token", accessToken);
			}else {
				accessToken = "errCode:" + wxAccessToken.getErrcode() + "," + "errMsg:" + wxAccessToken.getErrmsg();
			}
		}
		return accessToken;
	}
	@ResponseBody
	@RequestMapping("/getExpireTime")
	public String getExpireTime(@RequestParam String key){
		logger.info("come in getExpireTime method key {}",key);
		return String.valueOf(redisUtil.getExpireTime(key));
	}

	/**
	 * @author:dx
	 * @date:2018/10/10/0010
	 * @time:16:25
	 * @description:
	 * @param key
	 * @param expireTime
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/setExpireTime")
	public String setExpireTime(@RequestParam String key,@RequestParam long expireTime){
		return String.valueOf(redisUtil.expire(key,expireTime));
	}

}
